const {app, BrowserWindow, ipcMain, Menu, shell, Tray} = require('electron')
var win = null;
var imageBasePath = './';

function createWindow() {
    win = new BrowserWindow({
        width: 300,
        height: 300,
        x: 20,
        y: 20,
        //icon: './src/images/logo.png',
        frame: false,
        transparent: true, //设置透明
        webPreferences: {
            //devTools: false,
            nodeIntegration: true
        }
    })

    win.loadFile('./src/index.html'); //加载的html文件
    win.setMenu(null);
    // 设置窗口是否可以由用户手动最大化。
    win.setMaximizable(false);
    // 设置用户是否可以调节窗口尺寸
    win.setResizable(false);
    //win.setOverlayIcon('./src/images/logo.png', 'Description for overlay')

    try {
        win.setIcon(imageBasePath + 'src/images/logo.png');
    } catch (e) {
        imageBasePath = './resources/app/';
        win.setIcon(imageBasePath + 'src/images/logo.png');
    }
    win.setSkipTaskbar(true);
}

//app.whenReady().then()


var tray = null;
app.whenReady().then(() => {
    createWindow();
    tray = new Tray(imageBasePath + 'src/images/logo.png');
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '图层位置总在最前面', type: 'radio', click: function () {
                win.setAlwaysOnTop(true);
                win.show();
            }
        },

        {
            label: '图层位置总在最后面', type: 'radio', checked: true, click: function () {
                win.setAlwaysOnTop(false);
            }
        },

        {
            label: '显示主窗口',
            icon: imageBasePath + 'src/images/show.png',
            click: function () {
                win.show();
            }
        },
        {
            label: '最小化到托盘',
            icon: imageBasePath + 'src/images/min.png',
            click: function () {
                win.hide();
            }
        },
        {
            label: '退出程序',
            icon: imageBasePath + 'src/images/exit.png',
            click: function () {
                tray.destroy();
                app.quit();
                app.quit();//因为程序设定关闭为最小化，所以调用两次关闭，防止最大化时一次不能关闭的情况
            }
        }
    ])
    tray.setToolTip('live2d Desktop app\nmake by zhaoyijie\n(Aquarius wizard)')
    tray.setContextMenu(contextMenu)
    tray.on('click', function () {
        win.show();
    });
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        tray.destroy();
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
});

ipcMain.on('handelClose', function (res) {
    console.log("执行关闭操作");
    tray.destroy();
    app.quit();
})


ipcMain.on('open-url', (event, url) => {
    shell.openExternal(url);
});